package com.jrtc.base.util.ios;

import com.alibaba.fastjson.JSONObject;
import com.jrtc.base.util.payUtil.IosVerifyUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class IosPayUtil {
    static final Logger log = LoggerFactory.getLogger(IosPayUtil.class);

    public static boolean isSucc(String payload, String transactionId) {

        log.info("接口：openVipByIOS====开始");
        //验证
        String verifyResult = IosVerifyUtil.buyAppVerify(payload, 1);
        log.info("方法：buyAppVerify====返回值：verifyResult" + verifyResult);
        if (verifyResult == null) {
            return false;
        }

        JSONObject appleReturn = JSONObject.parseObject(verifyResult);
        String states = appleReturn.getString("status");
        log.info("值：states====" + verifyResult);

        //无数据则沙箱环境验证
        if ("21007".equals(states)) {
            verifyResult = IosVerifyUtil.buyAppVerify(payload, 0);
            log.info("沙盒环境，苹果平台返回JSON:" + verifyResult);
            appleReturn = JSONObject.parseObject(verifyResult);
            states = appleReturn.getString("status");
        }

        //验证成功
        if (("0").equals(states)) {
            String receipt = appleReturn.getString("receipt");
            log.info("receipt{}", receipt);
            JSONObject returnJson = JSONObject.parseObject(receipt);
            log.info("returnJson{}", returnJson);
            String inApp = returnJson.getString("in_app");
            log.info("inApp{}", inApp);
            List<HashMap> inApps = JSONObject.parseArray(inApp, HashMap.class);
            log.info("inApps{}", inApps);

            if (!CollectionUtils.isEmpty(inApps)) {
                log.info("===进入判断");
                ArrayList<String> transactionIds = new ArrayList<String>();
                for (HashMap app : inApps) {
                    log.info("===进入for循环");
                    transactionIds.add((String) app.get("transaction_id"));
                }
                //交易列表包含当前交易，则认为交易成功
                log.info("transactionId{}", transactionId);
                if (transactionIds.contains(transactionId)) {
                    log.info("交易成功");
                    return true;
                }

            }
        }
        return false;
    }


}